package com.tgy.leetcode;

import java.util.Arrays;

/**
 * @Author: tgy
 * @Date: 12/24/20 4:11 PM
 *
 *  https://leetcode-cn.com/problems/candy/
 */
public class _135_分发糖果_01 {

    public int candy(int[] ratings) {

        if (ratings == null || ratings.length == 0) {

            return 0;
        }

        if (ratings.length == 1) {

            return 1;
        }

        int sum = 0;

        int[] leftToRight = new int[ratings.length];
        int[] rightToLeft = new int[ratings.length];

        leftToRight[0] = 1;
        for (int i = 1; i < ratings.length; i++) {

            if (ratings[i - 1] < ratings[i]) {

                leftToRight[i] = leftToRight[i - 1] + 1;
            }else {

                leftToRight[i] = 1;
            }
        }

        rightToLeft[ratings.length - 1] = 1;
        for (int i = ratings.length - 2; i >= 0; i--) {

            if (ratings[i] > ratings[i + 1]) {

                rightToLeft[i] = rightToLeft[i + 1] + 1;
            }else {

                rightToLeft[i] = 1;
            }
        }

        for (int i = 0; i < ratings.length; i++) {

            sum += (Math.max(leftToRight[i],rightToLeft[i]));
        }

        return sum;
    }
}


